package com.yjj.demo.id.generator.dao;

import com.yjj.demo.id.generator.entity.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 *
 *
 * @author yangjiajia
 * @time 2021/6/27 16:40
 */
@Repository
public class IdGeneratorDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    public IdGenerator nextId(String module) {
        Query query = new Query();
        query.addCriteria(Criteria.where("module").is(module));

        Update update = new Update();
        update.inc("currentId");
        update.setOnInsert("createTime", System.currentTimeMillis());
        update.set("updateTime", System.currentTimeMillis());

        return mongoTemplate.findAndModify(query, update, FindAndModifyOptions.options().returnNew(true).upsert(true), IdGenerator.class);
    }
}
